class Solution {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int m = mat.length;
        int n = mat[0].length;
        int[][] dp = new int[m + 1][n + 1];
        //求前缀和数组
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1] + mat[i - 1][j - 1];
            }
        }
        int[][] anwser = new int[m][n];
        for(int i = 0; i < m; i ++){
            for(int j = 0; j < n; j++){
                //求左上点和右下点的坐标
                int x1 = (i - k < 0 ? 0 : i - k) + 1;
                int y1 = (j - k < 0 ? 0 : j - k) + 1;
                int x2 = (i + k > m - 1 ? m - 1 : i + k) + 1;
                int y2 = (j + k > n - 1 ? n - 1 : j + k) + 1;
                anwser[i][j] = dp[x2][y2] - dp[x2][y1 - 1] - dp[x1 - 1][y2] + dp[x1 - 1][y1 - 1];
            }
        }
        return anwser;
    }
}